/**
 * 
 */
package cn.jhz.filesharingsystem.web;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.jhz.filesharingsystem.model.User;

/**
 * @author asus
 *
 */
public class OnlineCheckInterceptor extends HandlerInterceptorAdapter{

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler)
			throws Exception {
			
		
	        HttpSession session = req.getSession();
	        ServletContext application = session.getServletContext();
	        User user = (User) session.getAttribute("loginUser");
	        Cookie cookies[] = req.getCookies();
	        
	        if(user != null && application.getAttribute(user.getEmail())!=null) {
	        	 if(!application.getAttribute(user.getEmail()).equals(session)){    
	 	        	//登录超时
	        		 if(cookies !=null && cookies.length > 0) {
	     				for (Cookie cookie : cookies) {
	     					if(cookie.getName().equals("userKey")) {
	     						cookie.setMaxAge(0);
	     						resp.addCookie(cookie);
	     					}else if(cookie.getName().equals("ssid")) {
	     						cookie.setMaxAge(0);
	     						resp.addCookie(cookie);
	     					}	
	     				} 
	        		 } 
	        		 resp.sendRedirect(req.getContextPath()+"/logout");
	 	        }
	        }
		return super.preHandle(req, resp, handler);
	}
	
}
